import { replace } from "lodash";
import {
  postMarkdown,
  getMarkdownTitles,
  removeMarkdown,
  buildChroma,
  ask,
  getMarkdown,
} from "@/apis";

function parseTitle(content: string): string {
  const newlineIndex = content.indexOf("\n");

  const removeSpecial = (val: string) => replace(val, "#", "");

  if (newlineIndex === -1) {
    return removeSpecial(content);
  } else {
    return removeSpecial(content.substring(0, newlineIndex));
  }
}

export default function useEditor({} = {}) {
  const saveContent = async ({ id, content }) => {
    return postMarkdown({ id, title: parseTitle(content) || "UnTitled", content });
  };
  const getNoteTitles = async () => {
    return getMarkdownTitles();
  };
  const removeContent = async ({ id }) => {
    await removeMarkdown({ id });
  };
  return {
    saveContent,
    getNoteTitles,
    removeContent,
    buildChroma,
    ask,
    getMarkdown,
  };
}
